﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using SaaS.Core;
using SaaS.Model.Entity.Blogs;
using XCore.Logger;

namespace Web.Blog.Controllers
{
    [Route("blog/[controller]")]
    [ApiController]
    public class ArticleController : BlogControllerBase
    {
        /// <summary>
        /// 本地缓存
        /// </summary>
        private readonly IMemoryCache _memoryCache;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="memoryCache"></param>
        public ArticleController(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
        }

        [HttpGet("{id}")]
        public ActionResult Info(int id)
        {
            if (_memoryCache.TryGetValue(id, out Article article))
            {
                return Ok(article);
            }
            else
            {
                article = BDC.Articles.FirstOrDefault(c => c.Id == id);
                if (article == null) throw new MessageException(CoreSetting.Error_ID);
                _memoryCache.Set(id, article, TimeSpan.FromHours(2));
                return Ok(article);
            }
        }

        [HttpPost]
        public ActionResult Message(int id)
        {
            return Ok(BDC.ArticleMessages.Where(c => c.ArticleId == id));
        }
    }
}